package com.example.woke;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zhongcai.online.R;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.adapter.Creditboradter;
import com.woke.adapter.Personboradter;
import com.woke.data.Datas_perbor1;
import com.woke.data.Datas_perbor2;
import com.woke.method.MyApp;
import com.wokeMy.view.turui.MyRealNameActivity;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.xl.xxl.imagecache.ImageLoader;

public class PersonborrAcitivity extends Activity implements OnItemClickListener, OnScrollListener {

	private ListView mListView;
	private LayoutInflater inflater;
	private ArrayList<Datas_perbor1> datalist = new ArrayList<Datas_perbor1>();
	private ArrayList<Datas_perbor2> datalist1 = new ArrayList<Datas_perbor2>();
	private Intent intent;
	private int threetype;
	private TextView mTtitle;
	private TextView mTtonext;
	private TextView mTextView;
	private RelativeLayout mBar;
	private MyApp application;
	private Myhotpreciver reciver;
	private Personboradter adapter;
	private AlertDialog alertDialog;
	private View footview;
	private int lastItem;
	private int currnet = 1;//������ҳ��
	private int totalpage;//�ܵ�ҳ��
	private Creditboradter adapter2;
	private ImageLoader imageLoader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personborr_acitivity);
		
		imageLoader = new ImageLoader(this);
		intent = getIntent();
		threetype = intent.getIntExtra("threetype", 0);
		inflater = getLayoutInflater();
		application = (MyApp) getApplication();
		intview();
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		reciver = new Myhotpreciver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.woke.personborrowinfoavtivity");
		PersonborrAcitivity.this.registerReceiver(reciver, filter);
		
	}
	
	@Override
	protected void onDestroy() {
		imageLoader.clearCache();
		imageLoader.clearMemoryCache();
		super.onDestroy();
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		PersonborrAcitivity.this.unregisterReceiver(reciver);
		
	}
	
	
	class Myhotpreciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Bundle extras = intent.getExtras();
			boolean sucessbor = extras.getBoolean("sucessbor", false);
			int parent = extras.getInt("parent", 101);
//			Log.e("��Ǯ�˳�", "ddd"+feyanUsersId);
//			int parent = extras.getInt("parent");
			if(parent != 101 && sucessbor == true){
				if(null != datalist && datalist.size() >0){
					datalist.remove(parent);
					adapter.notifyDataSetChanged();
				}
//				try {
//					Bitmap bitmap = Bimp.revitionImageSize(feyanUsersId);
//					if(parent == 0){
//						mZimage.setImageBitmap(bitmap);
//						uploadFile(feyanUsersId);
//					}else if(parent == 1){
//						mFimage.setImageBitmap(bitmap);
//						uploadFile(feyanUsersId);
//					}
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
			}
				
		}
	}

	private void intview() {
		
		
		mTextView = (TextView) findViewById(R.id.avperson_text_threetuo);
		if(threetype != 0){
			mTextView.setText("类型");
		}
		footview = getLayoutInflater().inflate(R.layout.footview, null);
		mListView = (ListView) findViewById(R.id.avperson_listview_list);
		mListView.addFooterView(footview);
		mListView.setOnItemClickListener(this);
		mListView.setOnScrollListener(this);
		footview.setVisibility(View.GONE);
		mTtitle = (TextView) findViewById(R.id.avperson_text_title);
		mTtonext = (TextView) findViewById(R.id.avperson_text_borrowmoney);
		mBar = (RelativeLayout) findViewById(R.id.avperson_progress_bar);
//		mBar.startAnimation(
//					AnimationUtils.loadAnimation(PersonborrAcitivity.this, R.anim.btn_rotate));
		findViewById(R.id.avperson_image_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		if(threetype == 0){
			mTtitle.setText("个人借贷");
			mTtonext.setText("借钱");
			getpersondata(currnet);
		}
		if(threetype == 1){
			mTtitle.setText("信用借贷");
			mTtonext.setText("借钱");
			getcreditdata(2);
		}
		if(threetype == 2){
			mTtitle.setText("抵押借贷");
			mTtonext.setText("借钱");
			getcreditdata(3);
		}
		
		mTtonext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(null == application.getDatas_load()){
//					Toast.makeText(BorrowActivity.this, "��δ��¼", Toast.LENGTH_SHORT).show();
					aralogid("还未登录","前往登录",1);
					
				}else if(application.getDatas_load().getUser_no_status().equals("1")){
					
					aralogid("还未实名认证","前往认证？",2);
					Toast.makeText(PersonborrAcitivity.this, "还未实名认", Toast.LENGTH_SHORT).show();
				}else if(application.getDatas_load().getUser_no_status().equals("2")){
					
//					aralogid("��δʵ����֤","ǰ����֤��",2);
					Toast.makeText(PersonborrAcitivity.this, "实名认证审核中，无操作权限", Toast.LENGTH_SHORT).show();
				}else{
					if(threetype == 0){
						intent.setClass(PersonborrAcitivity.this,BorrowActivity.class);
						startActivity(intent);
					}else if(threetype == 1){
						intent.setClass(PersonborrAcitivity.this,CreditActivity.class);
						intent.putExtra("threetype", 2);
						startActivity(intent);
					}else if(threetype == 2){
						intent.setClass(PersonborrAcitivity.this,CreditActivity.class);
						intent.putExtra("threetype", 3);
						startActivity(intent);
					}
				}
				
			}
		});
	}

	private void aralogid(String info,String kll,final int ppp){
		   alertDialog = new AlertDialog.Builder(this). 
	                setTitle(info). 
	                setMessage(kll). 
//	                setIcon(R.drawable.ic_launcher). 
	                setPositiveButton("确定", new DialogInterface.OnClickListener() { 
	                    @Override 
	                    public void onClick(DialogInterface dialog, int which) { 
//	                    Intent intent = new Intent();
	                    	if(ppp == 1){
	                    		intent.setClass(PersonborrAcitivity.this, LoadActivity.class);
	                    		startActivity(intent);
	                    	}else if(ppp == 2){
	                    		intent.setClass(PersonborrAcitivity.this, MyRealNameActivity.class);
	                    		startActivity(intent);
	                    	}
	                    	alertDialog.dismiss();
	                    } 
	                }). 
	                setNegativeButton("取消", new DialogInterface.OnClickListener() { 
	                    @Override 
	                    public void onClick(DialogInterface dialog, int which) { 
	                    	alertDialog.dismiss();
	                        // TODO Auto-generated method stub  
	                    } 
	                }).create(); 
	        alertDialog.show(); 
	}
	
	private void getcreditdata1(int typedd) {
		AsyncHttpClient ahc = new AsyncHttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(PersonborrAcitivity.this);    
		ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "quota");
		params.put("a", "quotaCredit");
		params.put("p", ""+currnet);
		params.put("type", typedd);
		if(null != application.getDatas_load()){
			params.put("user_id", application.getDatas_load().getId());
		}
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
//				Log.e("response", "ss"+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						String string = jsonObject.getString("data");
						ArrayList<Datas_perbor2> parseArray = (ArrayList<Datas_perbor2>) com.alibaba.fastjson.JSONArray.parseArray(string, Datas_perbor2.class);
						datalist1.addAll(parseArray);
						adapter2.notifyDataSetChanged();
					}else{
						Toast.makeText(PersonborrAcitivity.this, "数据获取失败！", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
//				if(datalist1.size() > 0){
//					adapter2.notifyDataSetChanged();
//					Creditboradter adapter = new Creditboradter(inflater,datalist1);
//				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(PersonborrAcitivity.this, "数据获取失败！", Toast.LENGTH_SHORT).show();
				Log.e("response", "失败"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
//				mBar.clearAnimation();
				mBar.setVisibility(View.GONE);
				Log.e("response", "完成");
			}
		});
	}
	
	private void getcreditdata(int typedd) {
		AsyncHttpClient ahc = new AsyncHttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(PersonborrAcitivity.this);    
		ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "quota");
		params.put("a", "quotaCredit");
		params.put("p", ""+currnet);
		params.put("type", typedd);
		if(null != application.getDatas_load()){
			params.put("user_id", application.getDatas_load().getId());
		}
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("response", "ss"+response);
				try {
					String flag = response.getString("flag");
					String info = response.getString("info");
					totalpage = Integer.parseInt(info);
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						String string = jsonObject.getString("data");
						ArrayList<Datas_perbor2> parseArray = (ArrayList<Datas_perbor2>) com.alibaba.fastjson.JSONArray.parseArray(string, Datas_perbor2.class);
						datalist1.addAll(parseArray);
					}else{
						Toast.makeText(PersonborrAcitivity.this, "数据获取失败！", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				if(datalist1.size() > 0){
					adapter2 = new Creditboradter(inflater,datalist1,imageLoader);
					mListView.setAdapter(adapter2);
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(PersonborrAcitivity.this, "数据获取失败！", Toast.LENGTH_SHORT).show();
				Log.e("response", "失败"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
//				mBar.clearAnimation();
				mBar.setVisibility(View.GONE);
				Log.e("response", "完成");
			}
		});
	}

	private void getpersondata(int currnet) {
		AsyncHttpClient ahc = new AsyncHttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(PersonborrAcitivity.this);    
		ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "quota");
		params.put("a", "quotaPerson");
		params.put("p", ""+currnet);
		params.put("type", "1");
//		params.put("user_id", "8");
		if(null != application.getDatas_load()){
//			Log.e(" application.getuser_id()",  " "+application.getuser_id());
			params.put("user_id", application.getDatas_load().getId());
		}
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("r上", ""+response);
				try {
					String flag = response.getString("flag");
					String info = response.getString("info");
					totalpage = Integer.parseInt(info);
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						String string = jsonObject.getString("data");
						ArrayList<Datas_perbor1> neslist = (ArrayList<Datas_perbor1>) com.alibaba.fastjson.JSONArray.parseArray(string, Datas_perbor1.class);
						datalist.addAll(neslist);
					}else{
						Toast.makeText(PersonborrAcitivity.this, "信息获取失败", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				if(datalist.size() > 0){
					adapter = new Personboradter(inflater,datalist,imageLoader);
					mListView.setAdapter(adapter);
				}
				
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(PersonborrAcitivity.this, "网络异常", Toast.LENGTH_SHORT).show();
				Log.e("课剪短发了e", "失败"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
//				mBar.clearAnimation();
				mBar.setVisibility(View.GONE);
				Log.e("response", "完成");
			}
		});
	}
	
	private void getpersondata1(int currnet) {
		AsyncHttpClient ahc = new AsyncHttpClient();
		PersistentCookieStore myCookieStore = new PersistentCookieStore(PersonborrAcitivity.this);    
		ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "quota");
		params.put("a", "quotaPerson");
		params.put("p", ""+currnet);
		Log.e("currnet", "%%%%"+currnet);
		params.put("type", "1");
//		params.put("user_id", "8");
		if(null != application.getDatas_load()){
//			Log.e(" application.getuser_id()",  " "+application.getuser_id());
			params.put("user_id", application.getDatas_load().getId());
		}
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("r上", ""+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						JSONObject jsonObject = response.getJSONObject("data");
						String string = jsonObject.getString("data");
						ArrayList<Datas_perbor1> neslist = (ArrayList<Datas_perbor1>) com.alibaba.fastjson.JSONArray.parseArray(string, Datas_perbor1.class);
						datalist.addAll(neslist);
						adapter.notifyDataSetChanged();
					}else{
						Toast.makeText(PersonborrAcitivity.this, "信息获取失败", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
//				if(datalist.size() > 0){
//					adapter.notifyDataSetChanged();
//					adapter = new Personboradter(inflater,datalist);
//					mListView.setAdapter(adapter);
//				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Toast.makeText(PersonborrAcitivity.this, "网络异常", Toast.LENGTH_SHORT).show();
				Log.e("课剪短发了e", "失败"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				Log.e("e", "e");
//				mBar.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				footview.setVisibility(View.GONE);
//				mBar.clearAnimation();
//				mBar.setVisibility(View.GONE);
				Log.e("response", "完成");
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
		if(threetype == 0){
			intent.setClass(PersonborrAcitivity.this,BorrowinfoActivity.class);
			intent.putExtra("id", datalist.get(arg2).getId());
			intent.putExtra("currno", arg2);//�����жϽ�Ǯ�ɹ���ɾ���ĵ�
			startActivityForResult(intent, 401);
		}else if(threetype == 1){
			intent.setClass(PersonborrAcitivity.this,CreditinfoActivity.class);
			intent.putExtra("id", datalist1.get(arg2).getId());
			intent.putExtra("user_id", datalist1.get(arg2).getUser_id());
			startActivity(intent);
		}else if(threetype == 2){
			intent.setClass(PersonborrAcitivity.this,CreditinfoActivity.class);
			intent.putExtra("id", datalist1.get(arg2).getId());
			intent.putExtra("user_id", datalist1.get(arg2).getUser_id());
			startActivity(intent);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		lastItem = firstVisibleItem + visibleItemCount - 1;  //��1����Ϊ������˸�addFooterView
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		//�����������ǣ������һ��item���������ݵ�����ʱ�����и���
		if(lastItem == (datalist.size()) || lastItem == (datalist1.size())){ 
			footview.setVisibility(view.VISIBLE);
			currnet = currnet + 1;
			Log.e("currnet", "\33");
			if(totalpage < currnet){
				footview.setVisibility(View.GONE);
			}else if(threetype == 0){
				getpersondata1(currnet);
			}else if(threetype == 1){
				getcreditdata1(2);
			}else if(threetype == 2){
				getcreditdata1(3);
			}			
//			Message msg = new Message();
//			msg.what = 20;
//			handler.sendMessage(msg);
//			handler.sendEmptyMessage(20);
			 
		}
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 20:
				Log.e("currnet", "currnet"+currnet);
				getpersondata1(currnet);
				break;
				
			default:
				break;
			}
		};
	};
	
}
